/*
 * rc_ppm.cpp
 *
 *  Created on: Jan 25, 2014
 *      Author: bohni
 */


#include "rc_ppm.h"

void rc_ppm_init() {

	// PORT CONFIG
	SIGNAL_OUT_DDR |= (1<<SIGNAL_OUT_PIN);
	SIGNAL_PIN_LOW


}

void send_rc_ppm( uint8_t value_array[], uint8_t nr_values ) {

	uint16_t sum = 0;

	for (uint8_t i = 0; i < nr_values; i++ ) {

//		FRAME
//				|			<------   FRAME_LENGTH_MS ------------------->			|
//				| STOP_TIME | MIN_TIME 	| SIGNAL_TIME	| ... 	| STOP_TIME | PAUSE |
//				 ___________									 ___________
//		sig inv	|			|___________|_______________|-------|			|_______|

//							 ___________________________					 _______
//		sig		|___________|			|				|-------|___________|		|

		#ifdef INVERT_SIGNAL
			SIGNAL_PIN_HIGH
		#else
			SIGNAL_PIN_LOW
		#endif

			_delay_us(STOP_TIME_US);

		#ifdef INVERT_SIGNAL
			SIGNAL_PIN_LOW
		#else
			SIGNAL_PIN_HIGH
		#endif

			_delay_us(MIN_TIME_US);
			for (uint8_t j = 0; j < ( value_array[i] ); j++) {
				_delay_us(SIGNAL_US_PER_LSB);
			}
		sum +=value_array[i];
	}

	#ifdef INVERT_SIGNAL
		SIGNAL_PIN_HIGH
	#else
		SIGNAL_PIN_LOW
	#endif

		_delay_us(STOP_TIME_US);

	#ifdef INVERT_SIGNAL
		SIGNAL_PIN_LOW
	#else
		SIGNAL_PIN_HIGH
	#endif

	// (FRAME_TIME in US) - (STOP + MIN_SINGAL)*NR_SINGALS
	uint16_t pause = FRAME_LENGTH_MS * 1000 - ( STOP_TIME_US + MIN_TIME_US ) * nr_values;
			pause-= STOP_TIME_US;

			pause -= sum * SIGNAL_US_PER_LSB;

			pause /= 100;

			for ( uint8_t i = 0; i < pause; i++ ){
				_delay_us(100);
			}

}
